const app = getApp()
const { get, del } = require('../../utils/request')

Page({
  data: {
    foods: [],
    page: 1,
    limit: 10,
    hasMore: true,
    isLoading: false
  },

  onLoad() {
    this.loadFoods()
  },
  onShow(){
    this.setData({
        page: 1,
        hasMore: true
      }, async () => {
        await this.loadFoods(false)
      
      })
  },

  async loadFoods(showLoading = true) {
    if (this.data.isLoading) return
    
    try {
      if (showLoading) {
        wx.showLoading({ title: '加载中' })
      }
      
      this.setData({ isLoading: true })
      
      const res = await get('/foods/my', {
        page: this.data.page,
        limit: this.data.limit,
        isCustom: true
      })
      
      if (res.code === 0) {
        const foods = res.data.foods.map(food => ({
          ...food,
          category: this.formatCategory(food.category)
        }))
        
        this.setData({
          foods: this.data.page === 1 ? foods : [...this.data.foods, ...foods],
          hasMore: foods.length === this.data.limit
        })
      } else {
        throw new Error(res.message)
      }
    } catch (error) {
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
    } finally {
      if (showLoading) {
        wx.hideLoading()
      }
      this.setData({ isLoading: false })
    }
  },

  formatCategory(category) {
    const categoryMap = {
      'staple': '主食',
      'meat': '肉类',
      'vegetable': '蔬菜',
      'fruit': '水果',
      'drink': '饮品',
      'other': '其他'
    }
    return categoryMap[category] || category
  },

  loadMore() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.setData({
        page: this.data.page + 1
      }, () => {
        this.loadFoods(false)
      })
    }
  },

  addFood() {
    wx.navigateTo({
      url: '/pages/food/add'
    })
  },

  editFood(e) {
    const food = e.currentTarget.dataset.food
    wx.navigateTo({
      url: `/pages/food/add?id=${food.id}`
    })
  },

  deleteFood(e) {
    const id = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '确定要删除这个食物吗？',
      success: (res) => {
        if (res.confirm) {
          this.handleDelete(id)
        }
      }
    })
  },

  async handleDelete(id) {
    try {
      wx.showLoading({ title: '删除中' })
      
      const res = await del(`/foods/${id}`)
      
      if (res) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        })
        
        // 重新加载第一页数据
        this.setData({
          page: 1,
          hasMore: true
        }, () => {
          this.loadFoods(false)
        })
      } else {
        throw new Error(res.message)
      }
    } catch (error) {
      wx.showToast({
        title: error.message || '删除失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true
    }, async () => {
      await this.loadFoods(false)
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom() {
    this.loadMore()
  }
}) 